package com.sdkj.dspservice.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.service.impl.CrudServiceImpl;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.modules.sys.dao.RoleDao;
import com.sdkj.dspservice.modules.sys.dao.RoleMenuDao;
import com.sdkj.dspservice.modules.sys.entity.Menu;
import com.sdkj.dspservice.modules.sys.entity.Role;
import com.sdkj.dspservice.modules.sys.entity.RoleMenu;
import com.sdkj.dspservice.modules.sys.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 菜单表service实现类
 *
 * @author tm
 * @version 2020/11/23 18:09
 */
@Service
@Transactional(readOnly = true)
public class RoleServiceImpl extends CrudServiceImpl<RoleDao, Role> implements RoleService {

    @Autowired
    private RoleMenuDao roleMenuDao;

    @Override
    public boolean saveOrUpdate(Role role) {
        List<Menu> menuList = role.getMenuList();
        boolean isNewRecord = role.isNewRecord();
        // 如果是更新则先删除菜单关联关系
        if(!isNewRecord){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("role_id", role.getId());
            roleMenuDao.delete(queryWrapper);
        }
        boolean result = super.saveOrUpdate(role);
        // 添加菜单关系
        if(CollectionsUtils.isNotEmpty(menuList)){
            for(Menu menu : menuList){
                RoleMenu roleMenu = new RoleMenu(role.getId(), menu.getId());
                roleMenuDao.insert(roleMenu);
            }
        }
        return result;
    }
}
